'''
GET meiduo_admin/statistical/day_active/
获取 当天的登录用户是数量
last_login 数据库的数据是 datetime【2021-1-27 10:05:05】
今天 【2021-1-27】 date --> datetime 【2021-1-27 00:00:00】

'''

# 日活用户
# 数据库中tb_users里的  last_login和date_joined 字段
from apps.users.models import User

from datetime import date
# filter(属性名称__比较运算符=值)
# 例如: filter(id__exact=1)


from rest_framework.views import APIView
from rest_framework.response import Response
class UserActiveAPIView(APIView):

    def get(self,request):
        # 1.获取今天的date
        today = date.today()
        # 2.过滤查询
        # count()获取数据
        count = User.objects.filter(last_login=today).count()

        return Response({'count':count})

# 当日下单用户
class UserOrderAPIView(APIView):

    def get(self,request):

        today = date.today()

        count = User.objects.filter(orderinfo__create_time__gte=today).count()

        return Response({'count':count})


# 月增用户统计
# 返回JSON数据格式
'''
[
    {
        "count": "用户量",
        "date": "日期"
    },
    {
        "count": "用户量",
        "date": "日期"
    },
    ...
]

'''
# 1: 获取当前日期和30天前的日期
# 2: 从30天前开始遍历
# 3: 获取每一天的新增数量
from datetime import timedelta
class MonthUserAPIView(APIView):

    def get(self,request):
        # 获取当前日期和30天前的日期
        today = date.today()
        before_date = today - timedelta(days=30)
        # 初始化一个字典列表
        data_list = []
        # 遍历获取每一天的新增用户量
        for i in range(0,30):
            # 从30天前开始 累加天数
            # 范围开始的日期
            start_date = before_date + timedelta(days=i)
            # 范围结束的日期
            end_date = before_date + timedelta(days=i+1)

            count = User.objects.filter(date_joined__gte=start_date,date_joined__lt=end_date).count()
            # 追加列表
            data_list.append({
                'count':count,
                'date':start_date
            })


